import { _decorator, Component, Node, ITriggerEvent, BoxCollider, Vec3, CameraComponent, find, ProgressBarComponent, Label, Prefab } from 'cc';
import { EventMgr } from '../../../Framework/Scripts/Managers/EventMgr';
import { poolManager } from '../../../Framework/Scripts/Managers/poolManager';
import { ResMgr } from '../../../Framework/Scripts/Managers/ResMgr';
import { SoundMgr } from '../../../Framework/Scripts/Managers/SoundMgr';
import myUtil from '../../../Framework/Scripts/Utils/myUtil';
import { constant } from '../constant';
import { GameApp } from '../GameApp';
import { UserData } from '../userData/UserData';
import { towerGun } from './towerGun';
const { ccclass, property } = _decorator;

@ccclass('towerTrigger')
export class towerTrigger extends Component {
    @property({ type: String, displayName: "对应塔编号" })
    private id: string = "1"

    private collider = null

    private myTower: Node = null


    private isStartSubGold: boolean = true//升级塔时候禁止金币计算

    private nextLevel: number = 1

    private bloodBarTs: ProgressBarComponent = null

    private bloodBarNode: Node = null

    private startPos: Vec3 = new Vec3()

    private isStartBar: boolean = false

    private nowPos: Vec3 = new Vec3()
    private nowTurret: Node = null
    private barLabel: Label = null

    private levelData = [
        {

            //0占位

        },

        {
            id: 1,
            coin: 100,



        },

        {
            id: 2,
            coin: 200,



        },


        {
            id: 3,
            coin: 300,



        }


    ]

    start() {

    }

    onLoad() {
        const nowLevel: number = GameApp.Instance.level
        console.log("当前关卡");
        
        if (nowLevel < 5) {
            this.levelData[1].coin = 100
            this.levelData[2].coin = 200
            this.levelData[3].coin = 300
        } else if (nowLevel >= 5 && nowLevel < 10) {
            this.levelData[1].coin = 200
            this.levelData[2].coin = 300
            this.levelData[3].coin = 400
        } else if (nowLevel >= 10 && nowLevel <20) {
            this.levelData[1].coin = 300
            this.levelData[2].coin = 400
            this.levelData[3].coin = 500
        } else{
            this.levelData[1].coin = 400
            this.levelData[2].coin = 500
            this.levelData[3].coin = 600
        }

        this.myTower = this.node.parent.parent.parent. getChildByName("towerRoot").getChildByName("tower" + this.id)
        this.startPos = this.myTower.getChildByName("barPos").getWorldPosition()
      // console.log("找到塔。", this.myTower);
        this.collider = this.node.getComponent(BoxCollider);

        this.collider.on('onTriggerExit', this.onTriggerExit, this);

        this.collider.on('onTriggerStay', this.onTriggerStay, this);

        this.bloodBarNode = poolManager.instance.getNode(ResMgr.Instance.getAsset("GUI", "fight/towerBloodBar"), GameApp.Instance.bloodBar_root)
        this.bloodBarTs = this.bloodBarNode.getChildByName("ProgressBar").getComponent(ProgressBarComponent);
        this.barLabel = this.bloodBarNode.getChildByName("str").getComponent(Label)
        // GameApp.Instance.Camera.node.getComponent(CameraComponent).convertToUINode(this.startPos, find('Canvas') as Node, this.nowPos) as Vec3;
        // this.bloodBarNode.setPosition(this.nowPos)
        if (this.nextLevel == 1) {
            this.barLabel.string = 0 + "/" + this.levelData[this.nextLevel].coin
        }
        this.bloodBarNode.active = false



    }
    private onTriggerStay(event: ITriggerEvent) {
        if (this.nextLevel > 3) {


            return
        }

        if (this.isStartBar) {
            return
        }
        if(GameApp.Instance.isGameOver){
            return
        }

        this.bloodBarNode.active = true

        this.isStartBar = true



    }
    private del() {
        if (this.bloodBarNode) {
            this.bloodBarNode.destroy()
            this.bloodBarTs = null
            this.bloodBarNode = null
            this.isStartBar = false
            this.node.parent. destroy()

        }
    }
    private onTriggerExit(event: ITriggerEvent) {
        this.bloodBarNode.active = false

        this.isStartBar = false

    }

    lateUpdate(dt: number) {
        if (GameApp.Instance.playerTs.isDie) {
            return
        }
        if(GameApp.Instance.isGameOver){
            return
        }
        if (!this.isStartBar) {
            return
        }
        if (this.nextLevel > 3) {
            return
        }
        if (!this.isStartSubGold) {
            return
        }
        if (this.bloodBarTs) {

            GameApp.Instance.Camera.node.getComponent(CameraComponent).convertToUINode(this.startPos, find('Canvas') as Node, this.nowPos) as Vec3;
            this.bloodBarNode.setPosition(this.nowPos)

            const bfb: number = 0.01
            const zong: number = this.levelData[this.nextLevel].coin



            const needCoin: number = Math.floor(zong * bfb)
            //  console.log("这一瞬间需要金币：", needCoin);


            //减去金币
            if (UserData.Instance.localData["gold"] >= needCoin) {

                UserData.Instance.localData["gold"] -= needCoin
                UserData.Instance.saveLocalData2()


                EventMgr.Instance.Emit(constant.EVENT_NAME.upGameStartTop, null)
                this.bloodBarTs.progress += bfb
                this.barLabel.string = Math.floor(this.bloodBarTs.progress * zong) + "/" + zong

            } else {
                //  console.log("金币不够");

                return
            }

            if (this.bloodBarTs.progress >= 1) {
                this.isStartSubGold = false

                this.bloodBarTs.progress = 0


                //根据塔等级创建塔
                const level = this.levelData[this.nextLevel]

                ResMgr.Instance.preloadAsset("prefab", "turret/turret" + level.id, Prefab, (asset) => {
                    if (this.nowTurret) {
                        poolManager.instance.putNode(this.nowTurret)
                        this.nowTurret = null
                    }

                    this.nowTurret = poolManager.instance.getNode(asset, this.myTower)
                    this.nowTurret.setWorldPosition(this.myTower.getChildByName("pos").getWorldPosition())
                    this.upEffect()
                    this.nextLevel++
                    // console.log("当前升级的塔：", this.nextLevel);
               

                    if (this.nextLevel > 3) {
                        //  console.log("满级销毁");
                        this.del()

                    } else {
                        const nextGold: number = this.levelData[this.nextLevel].coin
                        this.barLabel.string = 0 + "/" + nextGold
                        this.isStartSubGold = true
                    }

                })




            }

        }
    }
    private upEffect() {
        SoundMgr.Instance.playSound(ResMgr.Instance.getAsset("Sounds", "recovery"))

        const up: Node = poolManager.instance.getNode(ResMgr.Instance.getAsset("prefab", "effect/levelUp"), this.myTower)
        up.setWorldPosition(this.myTower.getChildByName("upEffect").getWorldPosition())


        up.layer = 8388608
        up.children.forEach(element => {
            element.layer = 8388608
            element.setScale(3.5, 3.5, 3.5)
        });


        myUtil.playEffect(up, false, true, 1, true)
    }
}


